<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-02-13
 * Time: 14:35:57
 * Info:
 */
defined('IN_YZMPHP') or exit('Access Denied');
yzm_base::load_controller('common', 'admin', 0);
yzm_base::load_sys_class('form', '', 0);
yzm_base::load_common('class/get_img_src.php', '', 0);
yzm_base::load_model("category_model", "admin");

class content extends common
{

    protected $model;

    const FLAG_NAME = [
        '1' => '置顶',
        '2' => '头条',
        '3' => '推荐',
        '4' => '跳转'
    ];

    public function __construct()
    {
        parent::__construct();
        $this->model = D('content');
    }

    public function init()
    {
        //获取栏目列表
        $categoryList = D('category')->field('id,name')->where(['delete_time' => 0])->select();
        $categoryList = array_column($categoryList, 'name', 'id');

        if (is_ajax()) {
            $limit = (int)input('limit', 10);
            $page  = (int)input('page', 1);
            $first = ($page - 1) * $limit;
            $field = input('field');
            $order = input('order');
            $key   = input('key');

            $where = "delete_time=0";
            if ( ! empty($key['username'])) {
                $where .= " and username = '{$key['username']}'";
            }
            if ( ! empty($key['role_id'])) {
                $where .= " and role_id = '{$key['role_id']}'";
            }
            if (isset($key['status']) && $key['status'] != '') {
                $where .= " and status = '{$key['status']}'";
            }
            if ( ! empty($field) && ! empty($order)) {
                $order = "{$field} {$order}";
            } else {
                $order = "is_top desc,update_time desc";
            }

            $field = "id,title,title_color,parent_id,image,flag,jump_url,weight,status,click,is_top,publish_time,create_time,update_time";
            $list  = $this->model->field($field)->where($where)->limit("{$first},{$limit}")->order($order)->select();
            foreach ($list as $key => $v) {
                $list[$key]['create_time']  = date("Y-m-d H:i:s", $list[$key]['create_time']);
                $list[$key]['update_time']  = date("Y-m-d H:i:s", $list[$key]['update_time']);
                $list[$key]['publish_time'] = date("Y-m-d H:i:s", $list[$key]['publish_time']);
                $list[$key]['flag_name']    = $this->flag_name($v['flag']);
                $list[$key]['parent_name']  = ! empty($categoryList[$v['parent_id']]) ? $categoryList[$v['parent_id']] : '';
            }

            $count = $this->model->total();
            return_json(['code' => 0, 'msg' => 'ok', 'data' => $list, 'count' => $count]);
        }
        include $this->admin_tpl('content/index');
    }

    public function add()
    {
        if (is_ajax()) {
            $param = input('post.');
            if (empty($param['title'])) {
                return_error('标题不能为空');
            }
            if (empty($param['parent_id'])) {
                return_error('栏目不能为空');
            }

            //自动提取缩略图
            if (isset($param['auto_image']) && empty($param['image'])) {
                $param['image'] = get_img_src::src($param['content']);
            }
            $param['is_top'] = ( ! empty($param['flag']) && in_array(1, $param['flag'])) ? 1 : 0;
            if ( ! in_array(4, $param['flag'])) {
                $param['jump_url'] = '';
            }
            $param['flag']        = ! empty($param['flag']) ? implode(',', $param['flag']) : '';
            $param['admin_id']    = cmf_get_admin_id();
            $param['description'] = empty($param['description']) ? str_cut(strip_tags($param['content']),
                250) : $param['description'];

            $param['publish_time'] = ! empty($param['publish_time']) ? strtotime($param['publish_time']) : time();
            $param['create_time']  = time();
            $param['update_time']  = time();

            try {
                $this->model->insert($param);
                return_success('保存成功');
            } catch (\Exception $e) {
                return_error($e->getMessage());
            }

        }
        $flag_name = self::FLAG_NAME;
        $pid_list  = category_model::getPidMenuList();

        include $this->admin_tpl('content/add');
    }

    public function edit()
    {
        if (is_ajax()) {
            $param = input('post.');
            if (empty($param['id'])) {
                return_error('id参数错误');
            }
            if (empty($param['title'])) {
                return_error('标题不能为空');
            }
            if (empty($param['parent_id'])) {
                return_error('栏目不能为空');
            }

            //自动提取缩略图
            if (isset($param['auto_image']) && empty($param['image'])) {
                $param['image'] = get_img_src::src($param['content']);
            }
            $param['is_top'] = ( ! empty($param['flag']) && in_array(1, $param['flag'])) ? 1 : 0;
            if ( ! in_array(4, $param['flag'])) {
                $param['jump_url'] = '';
            }
            $param['flag']        = ! empty($param['flag']) ? implode(',', $param['flag']) : '';
            $param['admin_id']    = cmf_get_admin_id();
            $param['description'] = empty($param['description']) ? str_cut(strip_tags($param['content']),
                250) : $param['description'];

            $param['publish_time'] = ! empty($param['publish_time']) ? strtotime($param['publish_time']) : time();
            $param['update_time']  = time();

            try {
                $this->model->update($param, ['id' => $param['id']]);
                return_success('保存成功');
            } catch (\Exception $e) {
                return_error($e->getMessage());
            }
        }
        $id = input('get.id');
        if (empty($id)) {
            showmsg('参数错误', 'stop');
        }
        $data                 = $this->model->where(['id' => $id])->find();
        $data['flag']         = explode(',', $data['flag']);
        $data['content']      = htmlspecialchars($data['content']);
        $data['publish_time'] = date("Y-m-d H:i:s", $data['publish_time']);

        $flag_name = self::FLAG_NAME;
        $pid_list  = category_model::getPidMenuList();

        include $this->admin_tpl('content/edit');
    }

    /**
     * 软删除-放入回收站
     */
    public function delete()
    {
        if (is_ajax()) {
            $id = input('id');
            if (empty($id)) {
                return_error("参数错误");
            }
            if (is_string($id)) {
                $id = [$id];
            }
            foreach ($id as $v) {
                //判断数据
                $data = $this->model->where(['id' => $v])->find();
                if (empty($data)) {
                    return_error("获取数据失败");
                }
                $this->model->update(['update_time' => time(), 'delete_time' => time()], ['id' => $v]);
            }
            return_success("删除成功，请到回收站中查看");

        }
    }

    /**
     * 分词输出
     * @return void
     */
    public function public_pullword()
    {
        $str = input('content');
        $res = pullword_fenci($str);
        return_success('ok', $res);
    }

    /*
     * flag 标签转换成字符串
     */
    private function flag_name($flag)
    {
        $flagArr   = explode(',', $flag);
        $flag_name = '';
        foreach ($flagArr as $v) {
            if ($v == 1) {
                $flag_name .= '<span class="hui-font-style layui-badge" title="'.self::FLAG_NAME[$v].'">'.mb_substr(self::FLAG_NAME[$v],
                        0, 1, 'utf-8').'</span>';
            } elseif ($v == 2) {
                $flag_name .= '<span class="hui-font-style layui-badge layui-bg-orange" title="'.self::FLAG_NAME[$v].'">'.mb_substr(self::FLAG_NAME[$v],
                        0, 1, 'utf-8').'</span>';
            } elseif ($v == 3) {
                $flag_name .= '<span class="hui-font-style layui-badge layui-bg-green" title="'.self::FLAG_NAME[$v].'">'.mb_substr(self::FLAG_NAME[$v],
                        0, 1, 'utf-8').'</span>';
            } elseif ($v == 4) {
                $flag_name .= '<span class="hui-font-style layui-badge layui-bg-purple" title="'.self::FLAG_NAME[$v].'">'.mb_substr(self::FLAG_NAME[$v],
                        0, 1, 'utf-8').'</span>';
            }

        }

        return $flag_name;
    }

}
